namespace two {
    export class Countdown extends egret.EventDispatcher {
        private txts:{txt:egret.BitmapText | egret.TextField, format:string}[] = [];
        public addTxtMonitor(txt:egret.BitmapText | egret.TextField, format:string):void {
            this.txts.push({txt:txt, format: format});
            if (this.maxSecond > 0) {
                txt.text = one.formatSecond(this.maxSecond, format);
            }
        }

        private bars:{bar:eui.ProgressBar}[] = [];
        public addBarMonitor(bar:eui.ProgressBar):void {
            this.bars.push({bar : bar});

            if (this.maxSecond > 0) {
                bar.maximum = this.maxSecond;
                bar.value = this.maxSecond;
            }
        }

        private reset(second:number):void {
            for (let i = 0; i < this.txts.length; i++) {
                let txtInfo = this.txts[i];
                txtInfo.txt.text = one.formatSecond(second, txtInfo.format);
            }

            for (let i = 0; i < this.bars.length; i++) {
                let barInfo = this.bars[i];
                barInfo.bar.value = second;
            }
        }

        private maxSecond:number = -1;

        private secId:number = -1;
		public start(second: number): void {
            this.maxSecond = second;

            for (let i = 0; i < this.bars.length; i++) {
                let barInfo = this.bars[i];
                barInfo.bar.maximum = this.maxSecond;
                barInfo.bar.value = this.maxSecond;
            }

			this.secId = one.secondUtils.addSecond(second, (leftSecond: number) => {
                this.reset(leftSecond);
			    
				if (leftSecond == 0) {
					one.secondUtils.removeSecond(this.secId);
                    this.dispatchEventWith(egret.Event.COMPLETE);
				}
			});
		}

        public stop():void {
            one.secondUtils.removeSecond(this.secId)
        }
    }
}